package com.tgy.atomic;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: tgy
 * @Date: 12/8/20 5:07 PM
 */
public class MyAtomicInteger {

    private transient volatile Integer val;

    private static long valOffset;

    private static Unsafe unsafe;

    static {

        try {

            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");

            theUnsafe.setAccessible(true);

            unsafe = (Unsafe) theUnsafe.get(null);

            valOffset = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("val"));

        }catch (Exception e) {

            throw new Error(e);
        }
    }

    public int incrementAndGet() {

        int except;
        do {

            except = val;
        }while (unsafe.compareAndSwapObject(this,valOffset,except,except+1));

        return val;
    }

    public static void main(String[] args) {



    }
}
